package com.heima.admin.filter;

import com.heima.model.admin.pojos.AdminUser;
import com.heima.utils.thread.AdminThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author:Dikk
 * @create: 2023-07-31 21:40
 * @Description: AdminTokenInterceptor
 */
@Component
public class AdminTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (StringUtils.isNotBlank(userId)) {
            AdminThreadLocalUtils.setUser(AdminUser.builder().id(Integer.valueOf(userId)).build());
        }
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminThreadLocalUtils.clear();
    }
}
